package com.jinyi.wwdeng.api_demo

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.jinyi.wwdeng.databinding.ActivityPickMediaBinding
import com.jinyi.wwdeng.utils.imagecovert.ImageConvert

/**
 * TODO: 系统图库组件demo
 */
class PickMediaActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPickMediaBinding
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    @SuppressLint("NotifyDataSetChanged", "Recycle")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 视图绑定
        binding = ActivityPickMediaBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 临时控件
        val result = binding.result
        val pick = binding.pick

        // 1-注册图库组件
        pickMedia =
            registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                if (uri != null) {
                    // 图片处理
//                    val stream = this@PickMediaActivity.contentResolver.openInputStream(uri)
//                    val bitmap = BitmapFactory.decodeStream(stream)
//                    result.setImageBitmap(bitmap)

                    ImageConvert.covert(
                        context = this@PickMediaActivity,
                        uri = uri
                    ) { localPath, bitmap ->
                        println("localPath: $localPath")
                    }

                } else {
                    println("No media selected")
                }
            }

        // 2-调起图库组件
        pick.setOnClickListener {
            pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }
    }
}